package com.spring.component.rabbitmq.config;

import com.spring.component.rabbitmq.listener.MyMessageListener;
import com.spring.component.rabbitmq.listener.Receiver;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置rabbitmq监听器
 * 
 * @author liushihua
 * @since 2018年04月25日
 */
@Configuration
public class ListenerConfig {

  @Autowired
  private Receiver receiver;
  @Autowired
  private MyMessageListener myMessageListener;

  /**
   * 注册一个简单的监听器容器 1、SimpleMessageListenerContainer 简单的监听器容器，不支持事务 2、DefaultMessageListenerContainer
   * 支持事务 3、ListenerContainer 不仅支持事务，还允许动态地管理JMS会话
   * 
   * @param connectionFactory
   * @return
   */
  @Bean
  public SimpleMessageListenerContainer listenerContainer(
      @Qualifier("connectionFactory") ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    // 设置connectionFactory
    container.setConnectionFactory(connectionFactory);
    // 设置消息json转换器
    container.setMessageConverter(new Jackson2JsonMessageConverter());
    // 队列
    container.setQueueNames("MSG_INBOUND_APP8075");
    container.setExposeListenerChannel(true);
    // 设置手动ack
    container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
    // 设置容器的消费者的线程数
    container.setConcurrentConsumers(1);
    // 设置容器的最大消费者数
    container.setMaxConcurrentConsumers(10);
    // 讲一个MessageListener实现注入到监听容器
    container.setMessageListener(receiver);
    return container;
  }

  // @Bean
  public SimpleMessageListenerContainer myListenerContainer(
      @Qualifier("connectionFactory") ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    // 设置connectionFactory
    container.setConnectionFactory(connectionFactory);
    // 设置消息json转换器
    container.setMessageConverter(new Jackson2JsonMessageConverter());
    // 队列
    container.setQueueNames("MSG_INBOUND_APP8075");
    container.setExposeListenerChannel(true);
    container.setMessageListener(myMessageListener);
    // 设置容器的消费者的线程数
    container.setConcurrentConsumers(1);
    // 设置容器的最大消费者数
    container.setMaxConcurrentConsumers(20);
    // container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
    return container;
  }
}
